package ui.fragment.homepagefragment.doworkfragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.DoTheWorkSelectAdapter;
import application.App;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.ListOfPapersBean;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import ui.activity.AddWacomActivity;
import ui.activity.AnswerSheetActivity;
import ui.activity.DoTheImageWorkActivity;
import utils.QiniuUploadUtils;
import utils.SPUtils;
import utils.StringUtils;

public class DoTheImageWorkFragment extends BaseNetFragment{
    private ImageView img_left,img_right;
    private Button bt_lookpaper;
    private List<ListOfPapersBean.mList.Questions> mLists = new ArrayList<>();
    private ScrollView scrollView;
//    private LinePathView paletteView;
    private String drawing_board_image = "";//手写板图片
    private ImageView check_pen,
            check_rubber,img_clean;
    private RecyclerView recy_xuanze;

//    private LinearLayout layout_pen,
//            layout_rubber,
    private LinearLayout    layout_wacom;
    private RichEditor ed_content;
    private ImageView img_photo,img_camera,img_update;
    private List<ListOfPapersBean.mList.Questions.Options> optionsList = new ArrayList<>();
    private DoTheWorkSelectAdapter selectAdapter;
    private int paper_question_id;//题目id
    private int student_task_id; // 学生作业id
    private int task_id;
    private int answer_id;//答题卡id
    private int maxSelectNum = 3;
//    private RecyclerView gv;
//    private GridImageAdapter adapter;
    private int i = 0;
    public static Fragment getInstance() {
        return new DoTheImageWorkFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {

    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_do_theimage_work;
    }

    @Override
    protected void findViews() {
        check_pen = getView(R.id.check_pen);
        check_rubber = getView(R.id.check_rubber);
        recy_xuanze = getView(R.id.rycl_xuanze);
        //输入答案
        ed_content = getView(R.id.ed_content);
        // img_wacom = getView(R.id.img_wacom);
        layout_wacom = getView(R.id.layout_wacom);
//        layout_pen = getView(R.id.layout_pen);
//        layout_rubber = getView(R.id.layout_rubber);
        img_clean = getView(R.id.img_clean);
        scrollView = getView(R.id.scrollView);
//        paletteView = getView(R.id.plt_wacom);

        img_left = getView(R.id.img_left);
        img_right = getView(R.id.img_right);
        bt_lookpaper = getView(R.id.bt_answer);
    }

    @Override
    protected void formatViews() {
//        check_pen.setOnClickListener(this);
//        check_rubber.setOnClickListener(this);
//        img_clean.setOnClickListener(this);
        initRichEditor();
        img_photo = getView(R.id.iv_picture_overkeyloard_addnote);
        img_camera= getView(R.id.iv_camera_overkeyloard_addnote);
        img_update = getView(R.id.iv_drawingboard_overkeyloard_addnote);
        img_photo.setOnClickListener(this);
        img_camera.setOnClickListener(this);
        img_update.setOnClickListener(this);
//        layout_pen.setBackgroundResource(R.color.check_color);

        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
        bt_lookpaper.setOnClickListener(this);
        ed_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    scrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    scrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        mLists = DoTheImageWorkActivity.mLists;
        student_task_id = DoTheImageWorkActivity.student_task_id;
        answer_id = DoTheImageWorkActivity.answer_id;
        if(mLists.size()>0){
            updateUi(0);
        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    String compressPath = localMedia.getCompressPath();

                    String qiniutoken = SPUtils.getInstance(App.getInstance()).getString("uptoken");
                    String key = System.currentTimeMillis() + "note.png";
                    QiniuUploadUtils.getInstance().uploadFile(compressPath, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                            final String image = yuming+key;
                            ed_content.insertImage(image, "\" style=\"max-width:100%");
                            selectList.clear();
                        }
                        @Override
                        public void onUploadFail(Error error) {

                        }
                    },qiniutoken);
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
//                    PictureFileUtils.deleteCacheDirFile(MainActivity.this);
                    // postMultiPhoto(selectList);
                    mLists.get(i).imglist = new ArrayList<LocalMedia>();
                    mLists.get(i).imglist.addAll(selectList);
                    //= selectList;
                    Log.i("imglist--->", "" + mLists.get(i).imglist);
//                    adapter.setList(selectList);
//                    adapter.notifyDataSetChanged();
                    break;
            }
        }else if(resultCode == 0){
            if(data == null){return;}
            if(!StringUtils.isNull(data.getStringExtra("filename"))){
                QiniuUploadUtils.getInstance().uploadFile(data.getStringExtra("filename"), new QiniuUploadUtils.UploadListener() {
                    @Override
                    public void onUploadSuccess(String key) {
                        hideLoadDialog();
                        String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                        final String image = yuming+key;
                        ed_content.insertImage(image, "\" style=\"max-width:100%");
                    }
                    @Override
                    public void onUploadFail(Error error) {
                        hideLoadDialog();
                        Looper.prepare();
                        toast("插入图片失败");
                        Looper.loop();
                    }
                },SPUtils.getInstance(getActivity()).getString("uptoken"));
            }else {
                i = data.getIntExtra("order",0);
                updateUi(i);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void initRichEditor() {
//        retNoteContent.setEditorHeight(DensityUtil.dip2px(EditNoteActivity.this,287));
        ed_content.setEditorFontSize(20);
        ed_content.setPlaceholder("请输入答案");
        ed_content.setEditorFontColor(getResources().getColor(R.color.font_black));
        ed_content.setPadding(33, 26, 33, 26);
        ed_content.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
//                content=text;
//                Logger.i("Logger","content"+text);
            }
        });
    }
    private void updateUi(int i) {
        DoTheImageWorkActivity.tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        optionsList = mLists.get(i).options;
        selectAdapter.setNewData(optionsList);
        Log.i("imglist--->", "" + mLists.get(i).answer_image);
        ed_content.setHtml(mLists.get(i).answer_image);
        //1.单选题，2.多选题，3.判断题，4.填空题，5.解答题，6.实验题，7.作文题
        switch (mLists.get(i).type_id) {
            case 1:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 2:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 3:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 4:
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 5:
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 6:
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            case 7:
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
            default:
                layout_wacom.setVisibility(View.VISIBLE);
                ed_content.focusEditor();
                break;
        }
    }
    @Override
    protected void formatData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy_xuanze.setLayoutManager(layoutManager);
        selectAdapter = new DoTheWorkSelectAdapter(R.layout.item_work_select, optionsList);
        recy_xuanze.setAdapter(selectAdapter);
        selectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(mLists.get(i).type_id == 2){
                    if(optionsList.get(position).getIsSelect() == 1){
                        optionsList.get(position).setIsSelect(0);
                    }else {
                        optionsList.get(position).setIsSelect(1);
                    }
                }else {
                    for (int i = 0; i < optionsList.size(); i++) {
                        if (position == i) {
                            optionsList.get(i).setIsSelect(1);
                            //optionsList.get(i).isSelect = 1;
                        } else {
                            optionsList.get(i).setIsSelect(0);
                            //optionsList.get(i).isSelect = 0;
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void getBundle() {

    }
    private List<LocalMedia> selectList = new ArrayList<>();
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_left:
                //上一张
                if (i <= 0) {
                    //toast("已是第一题");
                    return;
                }
                leftorRight();
                i--;
                updateUi(i);
                break;
            case R.id.img_right:
                //下一张
                if (i >= mLists.size() - 1) {
                    leftorRight();
                    Bundle bundle = new Bundle();
                    bundle.putInt("student_task_id", student_task_id);
                    bundle.putInt("answer_id", answer_id);
                    jumpTo(AnswerSheetActivity.class, 0,bundle);
                    //toast("已是最后一题");
                    return;
                }
                leftorRight();
                i++;
                updateUi(i);
                break;
            case R.id.bt_answer:
                //查看试卷
                ((DoTheImageWorkActivity)getActivity()).jumpToTsetPaper();
                break;
            //选择图片
            case R.id.iv_picture_overkeyloard_addnote:
                openPhoto();
                break;
            //拍照
            case R.id.iv_camera_overkeyloard_addnote:
                openCamera();
                break;
            //添加手写板图
            case R.id.iv_drawingboard_overkeyloard_addnote:
                jumpTo(AddWacomActivity.class,0);
                break;
        }
    }
    private void leftorRight() {
        if (mLists.size() > 0) {
            paper_question_id = mLists.get(i).paper_question_id;
            drawing_board_image = mLists.get(i).shouxieimg;
            mLists.get(i).answer_image = ed_content.getHtml();
            savedata();
        }
    }
    private void savedata() {
        Map<String, String> map = new HashMap<>();
        map.put("answer_id", "" + answer_id);
        map.put("paper_question_id", "" + paper_question_id);
        String answer = "";
        String answer_img = "";
        answer_img = mLists.get(i).answer_image;
        for (int i = 0; i < optionsList.size(); i++) {
            if (optionsList.get(i).isSelect == 1) {
                answer += optionsList.get(i).idx+",";
            }
        }
        if(StringUtils.isNull(answer)&&StringUtils.isNull(answer_img)){
            hideLoadDialog();
            return;
        }
        if(answer.length()>1){
            answer = answer.substring(0,answer.length()-1);
        }
        map.put("answer", "" + answer+""+answer_img);
        map.put("answer_image", "" + answer_img);
        map.put("drawing_board_image", "");
        post("Task/saveAnswer", map, BaseBean.class, true);
    }
    private void openPhoto() {
        PictureSelector.create(DoTheImageWorkFragment.this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(false)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
    private void openCamera() {
        PictureSelector.create(DoTheImageWorkFragment.this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }
}
